#! /usr/bin/env python
# -*- coding: utf-8 -*-


from playwright.sync_api import Page
from ui_automation_test.common.base_page import BasePage
from locators.dualPrevention.riskGrading.riskEvent.loc_risk_event_add import LocAddEvent
from locators.dualPrevention.riskGrading.riskEvent.loc_risk_event_edit import LocEditEvent
from locators.dualPrevention.riskGrading.riskEvent.loc_risk_event_search import LocSearchEvent
from locators.dualPrevention.riskGrading.riskEvent.loc_risk_event_view import LocViewEvent
from locators.dualPrevention.riskGrading.riskEvent.loc_risk_event_delete import LocDeleteEvent
from ui_automation_test.common.logger import logger


class AddRiskEvent(BasePage):

    def __init__(self, page: Page):
        super().__init__(page)
        self.switch_menu('双重预防机制')
        self.switch_menu('风险分析清单管理')
        self.switch_menu('安全风险事件')

    def add_event(self, object_name, unit_name, event_name, risk_level, identify_method, analyst, dangerous_factor, hazard_desc, control_measure_category1, control_measure_category2, control_method, inspection_cycle, inspection_cycle_unit, control_measure_description, hazard_description):
        logger.info('开始安全风险事件新增测试') 
        logger.info('点击新增按钮')
        # 只点击第一个"新增"按钮，避免匹配到表格内的"新增风险事件"按钮
        self.page.get_by_role('button', name='新增').first.click()
        logger.info('选择所属风险分析对象')
        self.select(LocAddEvent.loc_object_name, object_name)
        logger.info('选择所属风险分析单元')
        self.select(LocAddEvent.loc_unit_name, unit_name)          
        logger.info('选择风险事件名称')
        self.select(LocAddEvent.loc_event_name, event_name)
        logger.info('选择风险等级')
        self.select(LocAddEvent.loc_risk_level, risk_level)
        logger.info('选择辨识方法')
        self.select(LocAddEvent.loc_identify_method, identify_method)
        logger.info('选择分析人员')
        self.fill(LocAddEvent.loc_analysis_person, analyst)
        logger.info('选择导致该风险事件的危险因素')
        self.select(LocAddEvent.loc_dangerous_factor, dangerous_factor)
        logger.info('输入危害因素描述')
        self.fill(LocAddEvent.loc_hazard_factor_description, hazard_desc)
        # 新增管控措施信息
        logger.info('选择管控措施分类1')
        self.select(LocAddEvent.loc_control_measure_category1, control_measure_category1)
        logger.info('选择管控措施分类2')
        self.select(LocAddEvent.loc_control_measure_category2, control_measure_category2)
        logger.info('选择管控方式')
        self.select(LocAddEvent.loc_control_method, control_method)
        logger.info('清除巡检周期')
        self.clear_by_backspace(LocAddEvent.loc_inspection_cycle)
        logger.info('输入巡检周期')
        self.fill_number(LocAddEvent.loc_inspection_cycle, inspection_cycle)
        logger.info('选择巡检周期单位')
        self.select(LocAddEvent.loc_inspection_cycle_unit, inspection_cycle_unit, exact=True)
        logger.info('输入安全风险管控措施描述')
        self.fill(LocAddEvent.loc_control_measure_description, control_measure_description)
        logger.info('输入隐患排查内容')
        self.fill(LocAddEvent.loc_hazard_description, hazard_description)
        logger.info('提交')
        self.click(LocAddEvent.loc_submit)
        if self.wait_for_message("操作成功", timeout=10000):
            return {"success": True, "message": "新增操作完成"}
        else:
            self.wait_for_message("同一风险分析单元，安全风险事件名称不同,请检查!", timeout=10000)
            self.click(LocAddEvent.loc_cancel)
            return {"success": False, "message": "新增操作失败"}
        
    def edit_event(self, company, object_name, unit_name, event_name, edit_event_name, identify_method=None, analyst=None, dangerous_factor=None, hazard_desc=None):
        # 查询出要编辑的风险事件数据
        self.select(LocSearchEvent.loc_company_select, company)
        self.select(LocSearchEvent.loc_object_select, object_name)
        self.select(LocSearchEvent.loc_unit_name_select, unit_name)
        self.select(LocSearchEvent.loc_event_name_select, event_name, exact=True)
        self.click(LocSearchEvent.loc_search_button)
        self.page.wait_for_selector('.el-table__body', state='visible', timeout=10000)
        
        logger.info('开始安全风险事件编辑测试')
        
        logger.info('点击编辑按钮')
        self.click(LocEditEvent.loc_edit_button)
        logger.info('选择安全风险事件名称')
        self.select(LocEditEvent.loc_event_name, edit_event_name)
        logger.info('选择辨识方法')
        self.select(LocEditEvent.loc_identify_method, identify_method)
        logger.info('选择分析人员')
        self.fill(LocEditEvent.loc_analysis_person, analyst)
        logger.info('选择导致该风险事件的危害因素')
        self.select(LocEditEvent.loc_dangerous_factor, dangerous_factor)
        logger.info('输入危害因素描述')
        self.fill(LocEditEvent.loc_hazard_factor_description, hazard_desc)
        logger.info('提交')
        self.click(LocEditEvent.loc_submit)
        

    def search_event(self, event_name=None, company=None, object_name=None, unit_name=None, risk_level=None):
        """
        查询风险事件
        :param event_name: 风险事件名称
        :param company: 所属企业
        :param object_name: 所属风险分析对象
        :param unit_name: 所属风险分析单元
        :param risk_level: 风险等级
        """
        logger.info('开始风险事件查询')
        if company:
            logger.info(f'选择所属企业: {company}')
            self.select(LocSearchEvent.loc_company_select, company)
        if object_name:
            logger.info(f'选择所属风险分析对象: {object_name}')
            self.select(LocSearchEvent.loc_object_select, object_name)
        if unit_name:
            logger.info(f'选择单元名称: {unit_name}')
            self.select(LocSearchEvent.loc_unit_name_select, unit_name)
        if event_name:
            logger.info(f'选择风险事件名称: {event_name}')
            self.select(LocSearchEvent.loc_event_name_select, event_name, exact=True)
        if risk_level:
            logger.info(f'选择风险等级: {risk_level}')
            self.select(LocSearchEvent.loc_risk_level_select, risk_level)
        logger.info('点击查询按钮')
        self.click(LocSearchEvent.loc_search_button)

    def view_event(self, event_name):
        """
        查看风险事件详情
        :param event_name: 风险事件名称
        """
        logger.info('开始风险事件查看测试')
        logger.info('点击查看按钮')
        self.click(LocViewEvent.loc_view_button)
        self.page.wait_for_timeout(6000)
        logger.info('查看风险事件详情')
        # 先定位到卡片区域
        card = self.page.locator('div:has-text("安全风险事件信息")')
        # 只选卡片内 class 为 el-button--primary 且文本为“返回”的按钮
        back_btn = card.locator('button.el-button--primary', has_text="返回")
        back_btn.scroll_into_view_if_needed()
        back_btn.click()

    def delete_event(self, event_name):
        """
        删除风险事件
        :param event_name: 风险事件名称
        :return: 删除结果
        """

        logger.info(f'准备删除风险事件：{event_name}')
        try:
            # 查找风险事件行
            row = self.page.locator('.el-table__body tr').filter(has_text=event_name)
            if not row.is_visible():
                return {"success": False, "message": "未找到风险事件"}
            print("找到风险事件行")
            # 获取控制措施列的文本内容
            control_measures_locator = row.locator('td:nth-child(7)')  # 控制措施是第8列
            control_measures_count = control_measures_locator.inner_text(timeout=5000)
            print(control_measures_count)
            if control_measures_count == '0':
                # 点击删除按钮
                row.get_by_text('删除').click()
                # 等待并点击确认弹窗的“确定”按钮
                self.page.get_by_role('button', name='确定').click()

                # 等待成功提示（如果删除成功）
                self.wait_for_message("操作成功", timeout=10000)
                return {"success": True, "message": "删除操作完成"}

            else:
                # 点击删除按钮
                row.get_by_text('删除').click()
                # 等待并点击确认弹窗的“确定”按钮
                self.page.get_by_role('button', name='确定').click()
                self.wait_for_message("该风险事件已存在管控措施，不允许删除", timeout=10000)
                return {"success": False, "message": "删除操作失败"}

        except Exception as e:
            return {"success": False, "message": f"删除失败: {str(e)}"}